﻿
public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

public class Solution {
    public IList<int> InorderTraversal(TreeNode root)
    {
        List<int> res = new List<int>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        if (root is not null) stack.Push(root);
        TreeNode node;
        while (stack.Count != 0)
        {
            node = stack.Peek();
            if (node is not null)
            {
                stack.Pop();
                if (node.right is not null) stack.Push(node.right);
                
                stack.Push(node);
                stack.Push(null);
                if (node.left is not null) stack.Push(node.left);
            }
            else
            {
                stack.Pop();
                node = stack.Pop();
                res.Add(node.val);
            }
        }
        return res;
    }

    public static void Main(string[] args)
    {
        int?[] root = [1, null, 2, 3];
        
        // 创建二叉树
        TreeNode rootNode = CreateBinaryTree(root);

        Solution solution = new Solution();
        IList<int> res = solution.InorderTraversal(rootNode);
        foreach (int r in res)
        {
            Console.Write($"{r} ");
        }
    }

    private static TreeNode CreateBinaryTree(int?[] root)
    {
        if (root is null || root.Length == 0 || root[0] is null)
        {
            return null;
        }

        Queue<TreeNode> queue = new Queue<TreeNode>();
        TreeNode rootNode = new TreeNode(root[0].Value);
        queue.Enqueue(rootNode);

        int i = 1;
        TreeNode node;
        while (queue.Count != 0 && i < root.Length)
        {
            node = queue.Dequeue();

            if (root[i] is not null)
            {
                node.left = new TreeNode(root[i].Value);
                queue.Enqueue(node.left);
            }
            i++;
            
            if (i >= root.Length) break;
            if (root[i] is not null)
            {
                node.right = new TreeNode(root[i].Value);
                queue.Enqueue(node.right);
            }
            i++;
            
        }
        return rootNode;
    }
}